package com.sitech.portal.webHooks;


import com.sitech.ibnms.core.BaseIbnmsAction;
import org.codehaus.jackson.map.MapperConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.PropertyNamingStrategy;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.introspect.AnnotatedMethod;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * User: yanran
 * Date: 15-9-11
 * Time: 上午10:19
 * To change this template use File | Settings | File Templates.
 */
public class EventProcessorUtil  extends BaseIbnmsAction {

    private static ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.getSerializationConfig().set(SerializationConfig.Feature.WRITE_NULL_PROPERTIES, false);
        // 解决全大写属性被转成部分小写的问题
        mapper.setPropertyNamingStrategy(new PropertyNamingStrategy() {
            @Override
            public String nameForGetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName) {
                return translate(method, defaultName);
            }

            @Override
            public String nameForSetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName) {
                return translate(method, defaultName);
            }

            private String translate(AnnotatedMethod method, String defaultName) {
                String name = method.getName();
                // setXXX getXXX isXXX
                name = name.substring(name.length() - defaultName.length());
                return name.length() == 1 || name.matches(".*[a-z].*") ? defaultName : name;
            }
        });
        return mapper;
    }

    public static String toJSONWithOutNull(Object obj) {
        try {
            if (obj == null) {
                return null;
            } else {
                String str = objectMapper().writeValueAsString(obj);
                return str;
            }
        } catch (Exception ex) {
            throw new RuntimeException("转换Json异常!", ex);
        }
    }

    public static String getNowTime(){
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return formatter.format(new Date());
    }


}
